<?php
namespace TicTacToe\Model;

class Board {
	const X_MARK = "X";
	const Y_MARK = "O";
	const EMPTY_MARK = " ";
	
	const RESULT_INPROGRESS = 0;
	const RESULT_DRAW = 1;
	const RESULT_XWIN = 2;
	const RESULT_YWIN = 3;
	
	private $fields;
	private $winCombinations;
	
	public function __construct() {
		$this->winCombinations = array(
			array(0, 1, 2), array(3, 4, 5), array(6, 7, 8),
			array(0, 3, 6), array(1, 4, 7), array(2, 5, 8),	
			array(0, 4, 8), array(2, 4, 6),
		);
		
		$this->clear();
	}
	
	public function clear() {
		$this->fields[0] = self::EMPTY_MARK;
		$this->fields[1] = self::EMPTY_MARK;
		$this->fields[2] = self::EMPTY_MARK;
		$this->fields[3] = self::EMPTY_MARK;
		$this->fields[4] = self::EMPTY_MARK;
		$this->fields[5] = self::EMPTY_MARK;
		$this->fields[6] = self::EMPTY_MARK;
		$this->fields[7] = self::EMPTY_MARK;
		$this->fields[8] = self::EMPTY_MARK;
	}
	
	public function setFields($fields) {
		$this->fields = $fields;
	}
	
	public function GetFields() {
		return $this->fields;
	}
	
	public function GetField($index) {
		return $this->fields[$index];
	}
	
	public function placeSign($index, $sign) {
		if($this->fields[$index] != self::EMPTY_MARK) {
			return false;
		}
		
		$this->fields[$index] = $sign;
		return true;
	}
	
	public function whoseTurn() {
		$markCounts = array(self::X_MARK => 0, self::Y_MARK => 0, self::EMPTY_MARK => 0);
		for($i = 0; $i < 9; ++$i) {
			++$markCounts[$this->fields[$i]];
		}
		
		return $markCounts[self::X_MARK] <= $markCounts[self::Y_MARK] ? self::X_MARK : self::Y_MARK;
	}
	
	public function getGameResult() {
		// sprawdz czy gra sie skonczyla (wygrana)
		foreach($this->winCombinations as $combination) {
			$sign = $this->fields[$combination[0]];
		
			$validCombination = true;
			foreach($combination as $index) {
				if($sign != $this->fields[$index]) {
					$validCombination = false;
					break;
				}
			}
		
			if($sign == self::EMPTY_MARK) {
				continue;
			}
		
			if ($validCombination) {
				return $sign == self::X_MARK ? self::RESULT_XWIN : self::RESULT_YWIN;
			}
		}
		
		
		// sprawdz czy mozna jeszcze postawic jakis znak
		for($i = 0; $i < 9; ++$i) {
			if($this->fields[$i] == self::EMPTY_MARK) {
				return self::RESULT_INPROGRESS;
			}
		}
		
		return self::RESULT_DRAW;
	}
}